package com.itboye.sunsun.wxapi;

import com.itboye.sunsun.MainActivity;
import com.itboye.sunsun.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.PersonDataBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.controller.LoginedState;
import com.itboye.sunsun.login.ui.BindWeChatActivity;
import com.itboye.sunsun.login.ui.LoginActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.CodeErrorException;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;

	private IWXAPI api;
	private String code;

	public static String DISMISSFRAGMENT = "com.itboye.sunsun.dismiss";
	public static String NotifyPerson = "com.itboye.sunsun.notify.person";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.entry);

		// ͨ��WXAPIFactory��������ȡIWXAPI��ʵ��
		api = WXAPIFactory.createWXAPI(this, "wxa30658c4f4f6bbf4", false);

		api.handleIntent(getIntent(), this);
		SendAuth.Resp resp = new SendAuth.Resp(getIntent().getExtras());
		code = resp.code;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);

	}

	@Override
	public void onReq(BaseReq req) {

		WXEntryActivity.this.finish();

	}

	@Override
	public void onResp(BaseResp resp) {

		this.finish();

		int result = 0;

		code = ((SendAuth.Resp) resp).code;

		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			result = R.string.errcode_success;

			if (resp.transaction.equals("sessionwebpage")) {
				Toast.makeText(App.ctx, "分享成功", 0).show();
				// Intent intent=new Intent(DISMISSFRAGMENT);
				// sendBroadcast(intent);
				this.finish();

			}
			if (resp.transaction.equals("webpage")) {
				// Toast.makeText(App.ctx, "分享成功", 0).show();
				// Intent intent=new Intent(DISMISSFRAGMENT);
				// sendBroadcast(intent);
			}
			// resp.fromBundle(arg0);
			// Log.v("code", code);

			// 如果是微信登录
			if (resp.transaction.equals("login")) {

				wechatLogin(code);
				// WeChatNet.getInstance().getAccessToken(code);
			}
			// 如果是绑定手机
			else if (resp.transaction.equals("bind")) {
				wechatBind(code, (String) SPUtils.get(App.ctx, null, SPContants.USER_ID, ""));
				WXEntryActivity.this.finish();
			}

			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
			result = R.string.errcode_cancel;
			WXEntryActivity.this.finish();
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
			result = R.string.errcode_deny;
			WXEntryActivity.this.finish();
			break;
		default:
			result = R.string.errcode_unknown;
			WXEntryActivity.this.finish();
			break;
		}

		// Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

	private void wechatBind(String code, String uid) {

		MyJsonRequest<String> request = new MyJsonRequest.Builder<String>().apiVer("100").typeKey("BY_Weixin_bind")
				.param("code", code).param("uid", uid).requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String response) {
						// TODO Auto-generated method stub
						DebugLog.v("result", response.toString());
						Toast.makeText(App.ctx, "绑定成功", 0).show();
						Intent intent = new Intent(NotifyPerson);
						sendBroadcast(intent);

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						if (exception instanceof CodeErrorException) {
							DebugLog.v("bindmsg", msg);
							Toast.makeText(App.ctx, msg, 0).show();
						} else {
							Toast.makeText(App.ctx, exception.toString(), 0).show();

						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void wechatLogin(String code) {
		MyJsonRequest<PersonDataBean> request = new MyJsonRequest.Builder<PersonDataBean>().apiVer("100")
				.typeKey("BY_Weixin_login").param("code", code).requestListener(new XRequestListener<PersonDataBean>() {

					@Override
					public void onResponse(PersonDataBean response) {
						// TODO Auto-generated method stub
					
						
//						Toast.makeText(App.ctx, "username"+ response.getUsername(), 0).show();
//						Toast.makeText(App.ctx, "password"+ response.getPassword(), 10).show();
//						Toast.makeText(App.ctx, "uid"+ response.getUid(), 20).show();


						
						SPUtils.put(App.ctx, null, SPContants.USERNAME, response.getUsername());
						SPUtils.put(App.ctx, null, SPContants.IS_LOGINED, true);
						SPUtils.put(App.ctx, null, SPContants.EMAIL, response.getEmail());
						SPUtils.put(App.ctx, null, SPContants.NICK, response.getNickname());

						SPUtils.put(App.ctx, null, SPContants.PASSWORD, response.getPassword());
						SPUtils.put(App.ctx, null, SPContants.MOBILE, response.getMobile());
						SPUtils.put(App.ctx, null, SPContants.WX_Openid, response.getWxopenid());
						SPUtils.put(App.ctx, null, SPContants.USER_ID, response.getUid());
						SPUtils.put(App.ctx, null, SPContants.AVATAR_URL, response.getHead());

						Intent intent3 = new Intent("changeavart");
						sendBroadcast(intent3);
						LoginController.setLoginState(new LoginedState());
						// 手机认证
						if (response.getPhoneValidate().equals("1")) {

							SPUtils.put(App.ctx, null, SPContants.USERNAME, response.getUsername());
							SPUtils.put(App.ctx, null, SPContants.IS_LOGINED, true);
							SPUtils.put(App.ctx, null, SPContants.EMAIL, response.getEmail());
							SPUtils.put(App.ctx, null, SPContants.NICK, response.getNickname());

							SPUtils.put(App.ctx, null, SPContants.PASSWORD, response.getPassword());
							SPUtils.put(App.ctx, null, SPContants.MOBILE, response.getMobile());
							SPUtils.put(App.ctx, null, SPContants.WX_Openid, response.getWxopenid());
							// �����û�Id
							// Toast.makeText(App.ctx, response.getUid(),
							// 0).show();
							SPUtils.put(App.ctx, null, SPContants.USER_ID, response.getUid());
							// �����û�ͷ��
							SPUtils.put(App.ctx, null, SPContants.AVATAR_URL, response.getHead());

							LoginController.setLoginState(new LoginedState());
							

							Intent intent1 = new Intent("changeavart");
							sendBroadcast(intent1);

						} else if (response.getPhoneValidate().equals("0")) {

							
							
							//Toast.makeText(App.ctx, "哈哈哈哈", 0).show();
//							Intent intent = new Intent();
//							intent.putExtra("uid", response.getUid());
//							intent.setClass(WXEntryActivity.this, BindWeChatActivity.class);
//							response.toString();
//							startActivity(intent);
//
//							WXEntryActivity.this.finish();

						}
						WXEntryActivity.this.finish();
						Intent intent2 = new Intent(LoginActivity.LOGINEXIT);
						sendBroadcast(intent2);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						if (exception instanceof CodeErrorException) {
							Toast.makeText(App.ctx, msg, 0).show();
						} else {
							Toast.makeText(App.ctx, exception.toString(), 0).show();
						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

}